import numpy as np
from scipy.optimize import minimize

# 定义年收益率期望值
R = np.array([0.28, 0.20, 0.18, 0.10])

# 定义年收益率的协方差矩阵
cov_matrix = np.array(
[[0.400,0.055,0.015,0.013,],
[0.055,0.350,0.016,0.057,],
[0.015,0.016,0.028,0.078,],
[0.013,0.057,0.078,0.210,]])

# 定义目标年收益率阈值
R_min = 0.19

# 定义风险厌恶系数
risk_aversion = 0.5

# 定义二次规划目标函数
def objective(w):
    return - (np.dot(R, w) - risk_aversion * np.dot(w, np.dot(cov_matrix, w)))

# 定义约束条件1: 目标年收益率至少为 R_min
def constraint1(w):
    return np.dot(R, w) - R_min

# 定义约束条件2: 投资比例之和为1
def constraint2(w):
    return np.sum(w) - 1

# 定义优化问题
initial_guess = np.ones(4) / 4  # 初始猜测，均匀分配
constraints = ({'type': 'ineq', 'fun': constraint1},
               {'type': 'eq', 'fun': constraint2})
bounds = tuple((0, None) for _ in range(4))  # 投资比例非负

# 求解二次规划问题
result = minimize(objective, initial_guess, method='SLSQP', bounds=bounds, constraints=constraints)

# 输出结果
print("最优投资比例为：", result.x)
print("最优投资组合的年收益率为：", np.dot(R, result.x))
print("最优投资组合的方差为：", risk_aversion * np.dot(result.x, np.dot(cov_matrix, result.x)))




# # 定义年收益率的协方差矩阵
# cov_matrix = np.array(
# [[0.400,0.055,0.015,0.013,],
# [0.055,0.350,0.016,0.057,],
# [0.015,0.016,0.028,0.078,],
# [0.013,0.057,0.078,0.210,]])